package qgs.zisu.javaconcurrency.javaconcurrency.chapter12_ThreadGroup;

import com.sun.org.apache.xerces.internal.dom.PSVIAttrNSImpl;

import java.util.Arrays;

/**
 * @Author: 蔡翔
 * @Date: 2019/10/20 21:21
 * @Version 1.0
 */
public class ThreadGroupAPI {
    public static void main(String[] args) {
        ThreadGroup tg1 = new ThreadGroup("TG1");
        Thread t1 = new Thread(tg1,"T1"){
            public boolean flag = true;
            @Override
            public void run(){
                try {
                    Thread.sleep(10_000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        /*//线程组的daemon 就是 当这个组里的线程都执行完毕后，这个线程组就destory了。
        tg1.setDaemon(true);
        t1.start();*/

        /*//如果线程组里面有某个线程出现异常，这个方法就会把某个线程出现的异常返回给e
        //这里是 把t1出现的异常 返回给e
        Throwable e = new Throwable();
        tg1.uncaughtException(t1,e);*/


        ThreadGroup tg2 = new ThreadGroup(tg1,"TG2");
        Thread t2 = new Thread(tg2,"T2"){
            public boolean flag = true;
            @Override
            public void run(){
                try {
                    Thread.sleep(1_000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        t2.start();

        System.out.println(tg1.activeCount());
        System.out.println(tg1.activeGroupCount());
        // 线程组 中没有活跃的线程 才可以destroy
        //tg1.destroy();




        System.out.println("======================");
        Thread[] threads = new Thread[tg1.activeCount()];
        //tg1.enumerate(threads); 意思就是把 tg1里面 枚举出来的线程组放到 新定义的threads 线程组里面取。
        tg1.enumerate(threads);
        Arrays.asList(threads).forEach(System.out::println);

        System.out.println("===========================");
        tg1.enumerate(threads,false);  // 第二个参数是递归的意思
        Arrays.asList(threads).forEach(System.out::println);

        System.out.println("===========================");
        threads = new Thread[10];
        Thread.currentThread().getThreadGroup().enumerate(threads,false);
        Arrays.asList(threads).forEach(System.out::println);

        //tg1.interrupt();

    }
}
